#include <arpa/inet.h>
#include <pthread.h>

#ifdef OS_LINUX
#include <sys/socket.h>
#include <sys/types>
#endif

#include "base.h"

#define LISTEN_QUEUE_NUM 50
#define CLIENT_FP_NUM 10

int main(){

	struct sockaddr_in serverAddr,clientAddr;
	int listenFD;
	int clientFD[CLIENT_FP_NUM], cfdFlag[CLIENT_FP_NUM];
	int sockNum;
	char line[128];

	pthread_t pt;

	pid_t pchild;

	socklen_t socklen;

	memset(cfdFlag,0,CLIENT_FP_NUM);

	//serverAdd.sin_len=sizeof(struct sockaddr_in);

	bzero(&serverAddr,sizeof(listenFD));
	serverAddr.sin_family=AF_INET;
	serverAddr.sin_port=htons(3479);
	serverAddr.sin_addr.s_addr=htol(INADDR_ANY);    /** INADDR_ANY means let the kernel pick up the address for you when a tcp connection comes.*/

	//inet_pton(AF_INET,"127.0.0.1",&serverAdd.sin_addr);   ---  this function applies to both ipv4 and ipv6

	serverAddr=socket(AF_INET,SOCK_STREAM,0);
	bind(listenFD,(struct sockaddr *)&serverAddr,sizeof(serverAddr));

	listen(listenFD,LISTEN_QUEUE_NUM);

	for(;;){
		sockNum=getSockNum(cfdFlag);
		clientFD[sockNum]=accept(listenFD,&clientAddr,&socklen);
		if(0==(pchild=fork())){ /*Child process*/
			close(listenFD);

			for(;;){
				if(0!=read(clientFD[sockNum],line,sizeof(char)*128)){
					write(clientFD[sockNum],line,sizeof(char)*128);
				}else{
					printf("Client exited.\n");
					break;
				}
			}
			close(clientFD[sockNum]);

			exit(0);
		}
		/*main process*/
		close(clientFD[sockNum]);


	}

}

int getSockNum(int *sockFlag){

	int i,f;
	int rev=-1;

loop:
	for(i=0;i<CLIENT_FP_NUM;i++){
		if(sockFlag[i]==0){
			rev=i;
			break;
		}
	}

	if(rev==-1){
		sleep(5);
		goto loop;
	}else
		return rev;
}

//EXBOOL sendFile(char* fname){
//		EXBOOL rev=FALSE;
//
//
//		return rev;
//}
